package com.xm.security.core.impl;

import com.xm.common.Constants;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.Security;
import java.util.Base64;

/**
 * 描述: 3DES加密实现类
 *
 * @author chen-guipeng
 * @date 2022/7/21
 */
public class DESedeImpl {
    /**
     * 密钥算法
     */
    private String keyAlgorithm;
    /**
     * 加密算法
     */
    private String cipherAlgorithm;

    /**
     * 密钥长度
     */
    private int keySize;

    private byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8};

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public DESedeImpl(String keyAlgorithm, String cipherAlgorithm, int keySize) {
        this.keyAlgorithm = keyAlgorithm;
        this.cipherAlgorithm = cipherAlgorithm;
        this.keySize = keySize;
    }

    /**
     * 生成解密
     *
     * @return
     * @throws Exception
     */
    public byte[] getKey() throws Exception {
        KeyGenerator kg = null;
        if (this.keySize == 192) {
            kg = KeyGenerator.getInstance(keyAlgorithm, "BC");
        } else {
            kg = KeyGenerator.getInstance(keyAlgorithm);
        }
        kg.init(keySize);
        SecretKey key = kg.generateKey();
        return key.getEncoded();
    }

    /**
     * 生成解密
     *
     * @return
     * @throws Exception
     */
    public String getKeyString() throws Exception {
        byte[] keyData = getKey();
        String hex = Hex.toHexString(keyData);
        System.out.println("16进制密钥(" + keyData.length + ")：" + hex);
        return Base64.getEncoder().encodeToString(keyData);
    }

    /**
     * 加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public String encodeString(String data, String key) throws Exception {
        return Base64.getEncoder().encodeToString(this.encode(data, key));
    }

    /**
     * 加密
     *
     * @param dataStr
     * @param keyStr
     * @return
     * @throws Exception
     */
    public byte[] encode(String dataStr, String keyStr) throws Exception {
        return this.encode(dataStr.getBytes(StandardCharsets.UTF_8), Base64.getDecoder().decode(keyStr));
    }

    /**
     * 加密
     *
     * @param data     待加密数据
     * @param keyBytes 密钥
     * @return
     * @throws Exception
     */
    public byte[] encode(byte[] data, byte[] keyBytes) throws Exception {
        return this.crypt(data, keyBytes, Cipher.ENCRYPT_MODE);
    }

    /**
     * 解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public String decodeString(String data, String key) throws Exception {
        return new String(this.decode(data, key), Constants.DEFAULT_ENCODING);
    }

    /**
     * 解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public byte[] decode(String data, String key) throws Exception {
        return this.decode(Base64.getDecoder().decode(data), Base64.getDecoder().decode(key));
    }

    /**
     * 解密
     *
     * @param data 待解密数据
     * @param key  密钥
     * @return
     * @throws Exception
     */
    public byte[] decode(byte[] data, byte[] key) throws Exception {
        return this.crypt(data, key, Cipher.DECRYPT_MODE);
    }

    /**
     * 加密与解密处理
     *
     * @param data     待处理数据
     * @param keyBytes 密钥
     * @param mode     处理模式
     * @return
     * @throws Exception
     */
    private byte[] crypt(byte[] data, byte[] keyBytes, int mode) throws Exception {
        return this.crypt(data, this.toKey(keyBytes), mode);
    }

    /**
     * 加密与解密处理
     *
     * @param data
     * @param key
     * @param mode
     * @return
     * @throws Exception
     */
    private byte[] crypt(byte[] data, Key key, int mode) throws Exception {
        Cipher cipher = null;
        if (this.keySize == 192) {
            cipher = Cipher.getInstance(cipherAlgorithm, "BC");
            cipher.init(mode, key, new IvParameterSpec(iv));
        } else {
            cipher = Cipher.getInstance(cipherAlgorithm);
            cipher.init(mode, key);
        }
        return cipher.doFinal(data);
    }

    /**
     * 密钥转换
     *
     * @param keyBytes
     * @return
     * @throws Exception
     */
    private Key toKey(byte[] keyBytes) throws Exception {
        DESedeKeySpec dks = new DESedeKeySpec(keyBytes);
        SecretKeyFactory factory = null;
        if (this.keySize == 192) {
            factory = SecretKeyFactory.getInstance(keyAlgorithm, "BC");
        } else {
            factory = SecretKeyFactory.getInstance(keyAlgorithm);
        }
        return factory.generateSecret(dks);
    }

}
